package mgodb

import (
	"github.com/facebookgo/inject"
	"github.com/globalsign/mgo"
	"github.com/globalsign/mgo/bson"
	"github.com/pkg/errors"
	"jgt-oper/src/model"
	"jgt-oper/src/schema"
	"jgt-oper/src/service/mongo"
	"time"
)

// Employee 企业员工管理
type Employee struct {
	DB *mongo.DB
}

// Init 初始化
func (a *Employee) Init(g *inject.Graph, db *mongo.DB) {
	a.DB = db
	var val model.IEmployee = a
	g.Provide(&inject.Object{Value: val, Name: "IEmployee"})
}

// QueryPage 查询分页
func (a *Employee) QueryPage(params map[string]interface{}) (int, interface{}, error) {
	userDetail := new(schema.User)
	var err error
	//查询用户的详情，获取企业id
	err = a.DB.C(cUser, func(c *mgo.Collection) error {
		return c.Find(bson.M{"record_id": params["user_id"], "deleted": 0}).One(userDetail)
	})
	if err != nil {
		return 0, nil, errors.Wrapf(err, "查询当前用户信息详情发生错误")
	}

	var items []*schema.UserItemDetail
	//检查pageIndex pageSize参数
	pageIndex, indexOK := params["pageIndex"].(uint)
	pageSize, sizeOK := params["pageSize"].(uint)
	if !indexOK || !sizeOK {
		pageIndex = 1
		pageSize = 10
	}
	//检查gender参数
	gender := params["gender"]
	if gender == nil || gender == "" { //客户端没有传递性别参数
		params["gender"] = [...]int{1, 2}
	} else { //客户端传递了int类型参数
		genderInt, ok := gender.(int)
		if !ok {
			return 0, nil, errors.New("性别参数传递错误")
		}
		params["gender"] = []int{genderInt}
	}
	//检查start_time参数
	startTime := params["start_time"]
	if startTime == nil || startTime == "" { //客户端没有传递参数
		params["start_time"] = int64(0)
	} else { //客户端传递了int64类型参数

	}
	//检查end_time参数
	endTime := params["end_time"]
	if endTime == nil || endTime == "" { //客户端没有传递参数
		params["end_time"] = time.Now().Unix()
	} else { //客户端传递了int64类型参数
		//genderInt64,ok := gender.(int64)
		//if !ok {
		//	return 0,nil,errors.New("性别参数传递错误")
		//} else {
		//	params["end_time"] = genderInt64
		//}
	}

	queryCount := []bson.M{
		{"$match": bson.M{"enterprise_id": userDetail.EnterpriseID, "deleted": 0}},
		{"$lookup": bson.M{"from": "auth_user", "localField": "record_id", "foreignField": "_id", "as": "auth_user"}},
		{"$lookup": bson.M{"from": "oper_enterprise", "localField": "enterprise_id", "foreignField": "record_id", "as": "oper_enterprise"}},
		{"$unwind": bson.M{"path": "$auth_user", "preserveNullAndEmptyArrays": true}},
		{"$match": bson.M{"auth_user.deleted": 0}},
		{"$unwind": bson.M{"path": "$oper_enterprise", "preserveNullAndEmptyArrays": true}},
		{"$match": bson.M{"oper_enterprise.deleted": 0}},
		{"$addFields": bson.M{"tel": "$auth_user.tel"}},
		{"$addFields": bson.M{"enterprise_name": "$oper_enterprise.name"}},
		{"$project": bson.M{"_id": 0, "deleted": 0, "operator": 0, "auth_user": 0, "oper_enterprise": 0, "account": 0}},
		{"$match": bson.M{"nickname": bson.M{"$regex": params["nick_name"]}, "real_name": bson.M{"$regex": params["real_name"]}, "tel": bson.M{"$regex": params["tel"]}, "gender": bson.M{"$in": params["gender"]},
			"user_type": bson.M{"$regex": params["user_type"]},
			"$and":      []bson.M{{"created": bson.M{"$gte": params["start_time"]}}, {"created": bson.M{"$lte": params["end_time"]}}}}},
		{"$sort": bson.M{"created": -1}},
		{"$count": "total"},
	}

	queryItems := []bson.M{
		{"$match": bson.M{"enterprise_id": userDetail.EnterpriseID, "deleted": 0}},
		{"$lookup": bson.M{"from": "auth_user", "localField": "record_id", "foreignField": "_id", "as": "auth_user"}},
		{"$lookup": bson.M{"from": "oper_enterprise", "localField": "enterprise_id", "foreignField": "record_id", "as": "oper_enterprise"}},
		{"$unwind": bson.M{"path": "$auth_user", "preserveNullAndEmptyArrays": true}},
		{"$match": bson.M{"auth_user.deleted": 0}},
		{"$unwind": bson.M{"path": "$oper_enterprise", "preserveNullAndEmptyArrays": true}},
		{"$match": bson.M{"oper_enterprise.deleted": 0}},
		{"$addFields": bson.M{"tel": "$auth_user.tel"}},
		{"$addFields": bson.M{"enterprise_name": "$oper_enterprise.name"}},
		{"$project": bson.M{"_id": 0, "deleted": 0, "operator": 0, "auth_user": 0, "oper_enterprise": 0, "account": 0}},
		{"$match": bson.M{"nickname": bson.M{"$regex": params["nick_name"]}, "real_name": bson.M{"$regex": params["real_name"]}, "tel": bson.M{"$regex": params["tel"]}, "gender": bson.M{"$in": params["gender"]},
			"user_type": bson.M{"$regex": params["user_type"]},
			"$and":      []bson.M{{"created": bson.M{"$gte": params["start_time"]}}, {"created": bson.M{"$lte": params["end_time"]}}}}},
		{"$sort": bson.M{"created": -1}},
		{"$skip": (pageIndex - 1) * pageSize},
		{"$limit": pageSize},
	}

	count := new(schema.Count)
	err = a.DB.C(cUser, func(c *mgo.Collection) error {
		err = c.Pipe(queryCount).One(count)
		if err != nil {
			return errors.New("查询统计对应条件的用户总数出错")
		}
		return c.Pipe(queryItems).All(&items)
	})
	if err != nil {
		return 0, nil, err
	}
	return count.Total, items, nil
}

// QueryDetail 查询详情
func (a *Employee) QueryDetail(userID string) (*schema.User, error) {
	userDetail := new(schema.User)
	var err error
	err = a.DB.C(cUser, func(c *mgo.Collection) error {
		return c.Find(bson.M{"record_id": userID, "deleted": 0}).One(userDetail)
	})
	if err != nil {
		return nil, errors.Wrapf(err, "查询当前用户信息详情发生错误")
	}

	return userDetail, nil
}
